<template>
  <section class="todoapp">
    <HmHearder @addList="addList"></HmHearder>
    <HmBody
      :list="renderList"
      @listFlagChange="listFlagChange"
      @delList="delList"
      @SelectAll="SelectAll"
    ></HmBody>
    <HmFooter
      :listActive="listActive"
      :removeFlag="removeFlag"
      @delAllCompleted="delAllCompleted"
      :listType="listType"
      @screenList="screenList"
    ></HmFooter>
  </section>
</template>

<script>
import HmHearder from './components/HmHearder.vue'
import HmBody from './components/HmBody.vue'
import HmFooter from './components/HmFooter.vue'
// let arr = 'aa123bcdAA'
// console.log(arr.every(item => item == 1)); //every空数组调返回true，全部符合返回true，有一个不符合返回false
// console.log(arr.replace(/a/gi,'s'));
export default {
  components: {
    HmHearder,
    HmBody,
    HmFooter,
  },

  data() {
    return {
      list: JSON.parse(localStorage.getItem('taskList')) || [],
      // 定义筛选的判断值
      listType: 'all',
    }
  },
  methods: {
    // 修改完成或进行中状态
    listFlagChange(id) {
      this.list.forEach((item) => item.id === id && (item.flag = !item.flag))
    },
    // 添加事件 ，头部组件传的val添加到数据当中
    addList(val) {
      this.list = [
        ...this.list,
        {
          id: +new Date(),
          uname: val,
          flag: false,
        },
      ]
    },
    // 删除事件，将对应id的元素删除
    delList(id) {
      this.list = this.list.filter((item) => !(item.id === id))
    },
    // 删除所有已完成事件
    delAllCompleted() {
      this.list = this.list.filter((item) => !item.flag)
    },
    // 将底部筛选按钮传的值给到typelist来判定传入Body组件中的数据
    screenList(type) {
      this.listType = type
    },
    SelectAll() {
      this.list.forEach((item) => (item.flag = true))
    },
  },
  computed: {
    // 剩余未完成的数量，传给子组件Footer
    listActive() {
      return this.list.filter((item) => !item.flag).length
    },
    // 控制底部组件，清除所有已完成事件的显示状态
    removeFlag() {
      return this.list.some((item) => item.flag) //some 有一个符合的就返回true，没符合的返回false 空数组调返回 false
    },
    // 根据底部组件传的按钮，判断要传到body组件中的值
    renderList() {
      switch (this.listType) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },

  watch: {
    //  监听list，发生变化时放入本地储存
    list: {
      deep: true,
      immediate: true,
      handler(newVal) {
        localStorage.setItem('taskList', JSON.stringify(newVal))
      },
    },
  },
}
</script>

<style></style>
